package com.wcx.imitationwechatbilllist.details;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.wcx.imitationwechatbilllist.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @author: 魏从响
 * @date: 2025/10/24
 * @class: ListDetailsActivity
 */
public class ListDetailsActivity extends AppCompatActivity {

    private SmartRefreshLayout refresh_layout;
    private RecyclerView recycler_view;
    private List<ListDetailsBean> lists = new ArrayList<>();
    private long id=0;
    private ListDetailsAdapter adapter;
    private int page=1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_details);

        refresh_layout = findViewById(R.id.refresh_layout);
        recycler_view = findViewById(R.id.recycler_view);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ListDetailsActivity.this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        recycler_view.setLayoutManager(linearLayoutManager);
        adapter = new ListDetailsAdapter(ListDetailsActivity.this, R.layout.item_list_details, lists);
        recycler_view.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                ListDetailsBean item = (ListDetailsBean) adapter.getItem(position);
                Toast.makeText(ListDetailsActivity.this,"id="+item.getId(),Toast.LENGTH_SHORT).show();
            }
        });

        page=1;
        requestData();
        refresh_layout.setRefreshHeader(new ClassicsHeader(this));
        refresh_layout.setRefreshFooter(new ClassicsFooter(this));
        refresh_layout.setOnRefreshListener((refreshlayout)-> {
            //refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            id=0;
            page=1;
            requestData();
        });
        refresh_layout.setOnLoadMoreListener((refreshlayout)-> {
            //refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            page++;
            requestData();
        });

    }

    /**
     * @desc
     * @author 魏从响
     * @time 2025/10/24 16:07
     */
    private void requestData() {
        List<ListDetailsBean> newList = generateTestData();
        int type=2;
        switch (type){
            case 1://使用 DiffUtil,尤其适合数据集整体更换的场景。它能自动计算出最少的更新步骤。
                ListDetailsDiffCallback diffCallback = new ListDetailsDiffCallback(this.lists, newList);
                DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);
                // 模拟网络请求延迟
                new Handler(Looper.myLooper()).postDelayed(() -> {
                    this.lists.clear();
                    this.lists.addAll(newList);
                    diffResult.dispatchUpdatesTo(adapter); // 自动分发最优的更新通知
                    // 使用BRVAH的setDiffNewData方法，它会自动处理DiffUtil计算并在UI线程更新
                    adapter.setDiffNewData(newList);
                    refresh_layout.finishRefresh();//下来加载
                    refresh_layout.finishLoadMore();//上拉刷新
                }, 1500);
                break;

            case 2://使用 notifyItemRangeInserted()（上拉加载首选）
                // 模拟网络请求延迟
                new Handler(Looper.myLooper()).postDelayed(() -> {
                    // 首先，记录插入前列表的原始大小
                    int previousSize = adapter.getItemCount();
                    if (page==1&&lists.size()>0){
                        lists.clear();
                        lists.addAll(newList);
                    }else if(newList!=null&&newList.size()>0){
                        // 将新数据添加到原有列表的末尾
                        lists.addAll(newList); // newDataList 是你本次加载得到的新数据列表
                    }
                    // 然后，通知适配器有新项从 previousSize 位置开始，插入了 newDataList.size() 个
                    adapter.notifyItemRangeInserted(previousSize, newList.size());
                    refresh_layout.setEnableLoadMore(true);//有数据上拉加载成功
                    refresh_layout.finishRefresh();//下来加载
                    refresh_layout.finishLoadMore();//上拉刷新
                }, 1500);
                break;
        }
    }

    private List<ListDetailsBean> generateTestData() {
        List<ListDetailsBean> list = new ArrayList<>();
        // 添加账单数据
        for (int i = 1; i <10; i++) {
            Random random = new Random();
            int randomInt = random.nextInt(100);
            boolean isIncome = i % 3 == 0;
            String amount = (isIncome ? "+" : "-") + randomInt + "元";
            list.add(new ListDetailsBean(id,"消费名称","2025-10-25 13:0"+i+"00", amount));
            id++;
        }
        return list;
    }

}
